<?php
class AgentModel extends Model{
	protected $fields = array ('agt_id','agt_ip','agt_port','agt_type','agt_rank','agt_country','agt_province','agt_city','agt_lasttime','agt_checktime','agt_err', '_autoinc' => true, '_pk' => 'agt_id', ); 
	/*function save($data='',$options=array()) {
		if (is_array($data) && !isset($data['agt_lasttime'])) {
			$data['agt_lasttime']	=	time();
		}
		return parent::save($data,$options);
	}*/
	
	private $newIPCnt = 0;
	
	function getAvaible() {
		return $this->where('agt_rank in (1,2) and agt_province!="" and agt_err=0')->select();
	}
	
	/**
	 * 文本方式录入代理IP
	 * @param string $text
	 */
	function saveTextIp($text) {
		$lines = preg_split("#\r\n?|\n#", $text,-1,PREG_SPLIT_NO_EMPTY);
		if ($lines) {
			$data = array();
			foreach ($lines as $line){
				if (FALSE!==strpos($line, '阿里')) {
					continue;
				}
				//$line = preg_replace('#\s+#', '', $line);
				if (preg_match('#(\d+\.\d+\.\d+\.\d+)[ :\t]*(\d+)#', $line,$matches)) {
					$data[$matches[1]]	=	array(
						'agt_ip'	=>	$matches[1],
						'agt_port'	=>	$matches[2],
						'agt_type'	=>	$this->getProxyType($line),
					);
				}
			}
			return $this->addAll(array_values($data));
		}
	}
	
	/**
	 * 保存以div分隔的IP
	 * @param string $text 抓到的html代码
	 * @return Ambigous <boolean, string, unknown>
	 */
	function saveDivIp($text) {
		$text = str_replace(array(" ","\r","\n",'\t'), '', $text);
		$divs = explode('</div>', $text);
		if ($divs) {
			$data = array();
			foreach ($divs as $div){
				if (preg_match('#>(\d+\.\d+\.\d+\.\d+).*>(\d+)<#s', $div,$matches)) {
					$data[$matches[1]]	=	array(
						'agt_ip'	=>	$matches[1],
						'agt_port'	=>	$matches[2],
						'agt_type'	=>	$this->getProxyType($div),
					);
				}
			}
			return $this->addAll(array_values($data));
		}
	}
	
	function saveTrIP($text) {
		$trs = preg_split('#</tr>#', $text,-1,PREG_SPLIT_NO_EMPTY);
		if($trs){
			$data = array();
			foreach ($trs as $tr) {
				if (preg_match('#(\d+\.\d+\.\d+\.\d+)</td>.*>(\d+)</td>#s', $tr,$matches)) {
					$data[$matches[1]]	=	array(
						'agt_ip'	=>	$matches[1],
						'agt_port'	=>	$matches[2],
						'agt_type'	=>	$this->getProxyType($tr),
					);
				};
			}
			return $this->addAll(array_values($data));
		}
	}
	
	/**
	 * html代码录入代理IP
	 * @param string $html
	 */
	function saveTableIp($html) {
		$html = preg_replace('#\s+#', '', $html);
		$lines = explode('</tr>', $html);
		if ($lines) {
			$data = array();
			foreach ($lines as $line){
				if (FALSE!==strpos($line, '阿里')) {
					continue;
				}
				if (preg_match('#<td>(\d+\.\d+\.\d+\.\d+)</td>#', $line,$matchesIp)&& preg_match('#<td>(\d+)</td>#', $line,$matchesPort)) {
					$item	=	array(
						'agt_ip'	=>	$matchesIp[1],
						'agt_port'	=>	$matchesPort[1],
						'agt_type'	=>	$this->getProxyType($line),
					);
					$data[]	=	$item;
				}
			}
			return $this->addAll($data);
		}
	}
	
	public function addAll($dataList,$options=array(),$replace=false){
		$ret =  parent::addAll($dataList,$options,$replace);
		$delCnt = $this->dealRepeat();
		$this->delNoIP();
		if (FALSE!==$ret && FALSE!==$delCnt) {
			return $ret - $delCnt;
		}
		return $ret;
	}
	
	function delRepeat() {
		$sql = <<<SQL
DELETE M FROM _table_ AS M JOIN (
SELECT min( agt_id ) AS mid, agt_ip, agt_port, agt_type
FROM _table_
GROUP BY agt_ip, agt_port, agt_type
HAVING count( * ) >1
) AS S ON S.agt_ip = M.agt_ip
AND S.agt_port = M.agt_port
AND S.agt_type = M.agt_type AND M.agt_id > mid
SQL;
		$sql = str_replace('_table_', $this->getTableName(), $sql);
		return $this->execute($sql);
	}
	
	function updateRepeat() {
		$sql = <<<SQL
UPDATE _table_ M INNER JOIN (
	SELECT min(agt_id) as minid,agt_ip,agt_port,agt_type
	FROM _table_
	GROUP BY agt_ip,agt_port,agt_type
	HAVING COUNT(*) >1
) AS S
ON S.agt_ip = M.agt_ip
AND S.agt_port = M.agt_port
AND S.agt_type = M.agt_type AND S.minid = M.agt_id
SET M.agt_err = 1,M.agt_rank=0
WHERE M.agt_err > 1
SQL;
		$sql = str_replace('_table_', $this->getTableName(), $sql);
		return $this->execute($sql);
	}
	
	/**
	 * 处理重复记录
	 * @return boolean
	 */
	function dealRepeat() {
		$this->updateRepeat();
		return $this->delRepeat();
	}
	
	function delNoIP() {
		return $this->where('agt_ip like "127.%"')->delete();
	}
	
	private function getProxyType($text){
		$types = array('HTTPS','HTTP','SOCKS4','SOCKS5');
		foreach ($types as $t) {
			if(FALSE!==stripos($text,$t)){
				return $t;
			}
		}
		return 'HTTP';
	}
	
	function getIP4Location($rand=FALSE) {
		return $this->where('agt_country=""')->order($rand?'rand()':'agt_lasttime ASC')->find();
	}

	function getIP4checkLocationMuti( ){
		return $this->where('agt_country=""')->order('rand()')->getField('agt_id,agt_ip',50);
	}
	
	function where4Rank() {
		$time = time();
		$this->where("agt_lasttime + agt_err*3600*24 < $time and agt_rank<3 and agt_country='中国' and agt_province not in ('台湾','香港','澳门') AND (agt_rank>0 AND agt_err<8 OR agt_err < 3)");
	}
	
	/**
	 * 用户设置分页的，附带设置IP存活
	 * @param array $ipInfo IP信息
	 */
	function pageAlive($ipInfo) {
		$time = time();
// 		array('port'=>'agr_port','scheme'=>'agt_type');
		$where = array('agt_ip'=>$ipInfo['host'],'agt_err'=>0,'agt_rank'=>array('in',array(1,2,3)));
		if(isset($ipInfo['port'])){
			$where['agt_port'] = $ipInfo['port'];
			$where['agt_type'] = strtoupper($ipInfo['scheme']);
		}
		$this->where($where)->save(array('agt_lasttime'=>$time,'agt_checktime'=>$time));
	}

}
